package net.zhengxinyun.performance.App.service.townIndex;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.mapper.TownIndexMapper;
import net.zhengxinyun.performance.App.service.BaseIndexService.BaseIndexService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.TownEntity;
import net.zhengxinyun.performance.filter.TownFilter;
import net.zhengxinyun.performance.filter.TownIndicatorsFilter;
import net.zhengxinyun.performance.filter.TownScoreFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownScoreEntityMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sound.sampled.DataLine;
import javax.xml.crypto.Data;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TownIndexServiceImpl  extends BaseIndexService implements TownIndexService  {

    @Autowired
    private TownIndexMapper apptTownIndexMapper;
    @Autowired
    private TownIndicatorsEntityMapper webTownIndexMapper;
    @Autowired
    private DepartmentEntityMapper deptMapper;
    @Autowired
    private TownScoreEntityMapper townScoreMapper;
    @Autowired
    private TownMapper townMapper;//权重表


    @Override
    public List<TownIndicatorsFilter> getAllTownIndex(TownIndicatorsFilter filter) {
        List<TownIndicatorsFilter> allTownIndexs = apptTownIndexMapper.getAllTownIndexs(filter);

        //filterInditors(allTownIndexs,)
        return  allTownIndexs;
    }


    //查看指标分数
    @Override
    public List<ScoreDTO> getIndexScore(TownIndicatorsFilter filter, UserFilter userFilter) {


        List<DepartmentEntity> townList = deptMapper.selectForDepartment(null, "乡镇",null);

        String datetime = filter.getDateTime();
        if(StringUtils.isBlank(datetime))
        {
            datetime= DateUtils.getLastMonth();
        }
        List<ScoreDTO>  scoredtoList  = new ArrayList<>();

        for (DepartmentEntity town : townList) {

            List<TownScoreFilter> scoreList = townScoreMapper.queryDepartScore(town.getDepartcode(), datetime);
            double rate=0;
            int weightSum = scoreList.stream().mapToInt(TownScoreFilter::getIntWeight).sum();//总权值
            double sumScore = scoreList.stream().mapToDouble(TownScoreFilter::getDoubleFinalScore).sum(); // 总得分
            if(sumScore!=0)
            {
                //得分率
                rate= (sumScore / weightSum )*100;
                rate = Util.keepNumberFormat(2,rate);
            }



            scoredtoList.add(new ScoreDTO( Util.keepNumberFormat(2,sumScore)   ,rate ,weightSum, 0,town.getDepartAddr(),town.getDepartcode(),datetime ));

        }

       /// System.out.println(scoredtoList);
        // 计算排名 并列排名
        List<Map.Entry<Double, List<ScoreDTO>>> datalist = scoredtoList.stream().collect(
                Collectors.groupingBy(ScoreDTO::getScore)
        ).entrySet().stream().sorted((o1, o2) -> -Double.compare(o1.getKey(), o2.getKey())).collect(Collectors.toList());

        int rank =1;
        for (Map.Entry<Double, List<ScoreDTO>> item : datalist) {
            int temRank =rank;
            item.getValue().forEach(scoreDTO -> scoreDTO.setRank(temRank));
            rank=rank+item.getValue().size();
        }
        //从高到底排序
        Collections.sort(scoredtoList, new Comparator<ScoreDTO>() {
            @Override
            public int compare(ScoreDTO o1, ScoreDTO o2) {
                return  -Double.compare(o1.getScore(),o2.getScore());
            }
        });

      /*  //排名 排序
        Collections.sort(scoredtoList, new Comparator<ScoreDTO>() {
            @Override
            public int compare(ScoreDTO o1, ScoreDTO o2) {
                return -Double.compare(o1.getScore(),o2.getScore());
            }
        });
        int rank=0;
        int no =0;
        double lastScore =-1;
        for (ScoreDTO dto : scoredtoList) {

            if(Double.compare(lastScore,dto.getScore())!=0)
            {
                lastScore=dto.getScore();
                rank=rank+1+no;
                no =0;
            }else {
                no++;
            }
            dto.setRank(rank);
        }*/

        return scoredtoList;
    }


    @Override
    public List<ScoreDTO> queryYearIndexInfo(String indexid, String townid, String year) {
        List<TownScoreFilter> scoreList = townScoreMapper.queryAfterImport(indexid, townid, null);
        //单个指标 所有数据
        // datetime  当前年份
        TreeMap<String,String> datemap = Util.yearmonth(year);//当年所有月份

        List<ScoreDTO> list = new ArrayList<>();

        for (Map.Entry<String,String> iter: datemap.entrySet() )
        {
            String month=iter.getValue();

            List<TownScoreFilter> tempList = scoreList.stream().filter(filter -> filter.getDateTime().equals(month)).collect(Collectors.toList());
            if(ObjectUtils.isNotBlank(tempList))
            {
                TownScoreFilter obj = tempList.get(0);

                list.add( new ScoreDTO(DataUtil.StringToLong(obj.getId()),
                        DataUtil.doubleParse(obj.getFinalScore()),
                        DataUtil.doubleParse(obj.getScore()),
                        obj.getIntWeight(),0,null,null,month,null,null

                )   );
            }else {
                list.add(new ScoreDTO(
                        new Long(0),0,0,0,0,null,null,month,null,null
                ));
            }


        }





        return list;
    }


    //单个乡镇下所有指标得分
    @Override
    public List<TownIndicatorsFilter> getSingleTownIndexScore(TownIndicatorsFilter filter) {
        List<TownIndicatorsFilter> indexScore = townScoreMapper.getIndexScore(filter);
        return indexScore;
    }

    //单个指标 指标详情
    @Override
    public List<TownEntity> SingleIndexInfo(String indexId, String departCode, String datetime) {
        TownFilter townFilter = new TownFilter();
        townFilter.setIndexId(indexId);
        townFilter.setDepartcode(departCode);
        townFilter.setDatetime(datetime);

        List<TownEntity> townEntities = townMapper.selectWeight(townFilter);

      //  townEntities.forEach(entity -> System.out.println(entity.getTownName()));

        return  townEntities;
    }




}
